#include "PDTListOfStatements.h"
#include "PDTCodeGraph.h"
#include "PDTFunction.h"

void PDTListOfStatements::addStatement(PDTStatement &newStatement) {

	addChild(&newStatement);
	newStatement.addParent(this);
}

PDTListOfStatements::PDTListOfStatements(PDTCodeGraph & CG) :
	PDTStatement(CG) {
}

PDTListOfStatements::PDTListOfStatements(PDTCodeGraph & CG,
		PDTStatement & newStatement) :
	PDTStatement(CG) {
	addStatement(newStatement);
}

PDTListOfStatements::PDTListOfStatements(PDTCodeGraph & CG, vector<
		PDTStatement*> &statementList) :
	PDTStatement(CG) {
	int size = statementList.size();
	for (int i = 0; i < size; i++) {
		addChild(statementList[i]);
		statementList[i]->addParent(this);
	}
}


bool PDTListOfStatements::eval(PDTCodeGraph &CG) //Evaluate all statements in the list except if they are
									//postconditions, preconditions or behaviors
{
	int size = children.size();
	for (int i = 0; i < size; i++)
	{
		if (children[i]->isAssign())
		{
			PDTAssign* assign = dynamic_cast<PDTAssign*>(children[i]);
			if (assign->getChildren()[1]->isNumVar())
			{
				PDTNumVar *variable = dynamic_cast<PDTNumVar*>(assign->getChildren()[1]);
				string s = variable->getName();
				if (s.substr(s.size()-2, 2) == "rv") //if we reach a function call
				{

					string funcCallName = s.substr(0, s.size()-4);
					PDTFunctionDec* funcCall = (PDTFunctionDec*)(CG.findFunctionCall(funcCallName));
					//Recursive functions handling
					if (funcCallName == (funcCall)->getName())
					{
						PDTFunctionDec* funcClone = (PDTFunctionDec*)funcCall->clone(CG);
						PDTVar* retVarOld = funcCall->getReturnVar();
						retVarOld = funcClone->getReturnVar();
					}
					if (!(funcCall->eval(CG)))
						return false;
				}
			}
		}

		if (!children[i]->isPreCondition() && !children[i]->isPostCondition() && !children[i]->isBehaviors())
			if (!(children[i]->eval(CG)))
				return false;
	}
	return true;
}

